package webserver;

import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import java.util.concurrent.atomic.AtomicReference;

public class WebServer {
    private final HttpServer server;

    public WebServer(AtomicReference<String> heroes) {
        server = HttpServer.createSimpleServer("/", 4080);

        server.getServerConfiguration().addHttpHandler(getHandler(heroes), "/heroes");
    }

    private HttpHandler getHandler(final AtomicReference<String> toReturn) {
        return new HttpHandler() {
            public void service(Request request, Response response) throws Exception {
                response.setContentType("application/json");
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.getWriter().write(toReturn.get().toCharArray());
            }
        };
    }

    public void start() {
        new Thread(() -> {
            try {
                server.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
